<template>
  <div class="container">
    <!-- <data-view
      propViewKey="fsd_user"
      propViewForm="fsd/user/detail.vue"
      :propFlowKey="propFlowKey"
    />-->
    <div>
      <!-- 功能条 -->
      <el-row class="buttonRow">
        <el-col :span="2">
          <el-button type="primary" size="mini" @click="openCreateFormDialog">创建用户</el-button>
        </el-col>
        <el-col :span="2">
          <el-button type="primary" size="mini" :loading="synchronizeUsersBtn" @click="synchronizeUsers">同步用户</el-button          >
        </el-col>
        <el-col :span="20">
          <el-input
            v-model="getReq.keyword"
            size="mini"
            placeholder="请输入关键词..."
            clearable
            @keyup.enter.native="search"
            @clear="clearKeyword"
          >
            <el-button slot="append" icon="el-icon-search" @click="search" />
          </el-input>
        </el-col>
      </el-row>
      <!-- 列表 -->
      <el-row class="tableRow">
        <div class="tableDiv">
          <el-table :data="tableAry" border stripe @expand-change="expandTable">
            <el-table-column label="序号" prop="index" width="50px" :show-overflow-tooltip="true" />
            <el-table-column label="详情" width="50px" type="expand">
              <template slot-scope="props">
                <el-form label-position="left" inline class="table-expand">
                  <el-form-item label="拥有权限">
                    <span>{{ props.row.hasRoles }}</span>
                  </el-form-item>
                  <el-form-item label="所属用户群">
                    <span>{{ props.row.hasGroups }}</span>
                  </el-form-item>
                  <el-form-item label="具备智能柜的使用权">
                    <span>{{ props.row.hasChests }}</span>
                  </el-form-item>
                  <el-form-item label="具备智能柜组的使用权">
                    <span>{{ props.row.hasChestGroups }}</span>
                  </el-form-item>
                  <el-form-item label="Id">
                    <span>{{ props.row.id }}</span>
                  </el-form-item>
                  <el-form-item label="创建时间">
                    <span>{{ props.row.gmtCreate }}</span>
                  </el-form-item>
                  <el-form-item label="更新时间">
                    <span>{{ props.row.gmtModified }}</span>
                  </el-form-item>
                </el-form>
              </template>
            </el-table-column>
            <el-table-column label="姓名" prop="userName" width="100px" :show-overflow-tooltip="true" />
            <el-table-column label="工号" prop="jobNumber" width="150px" :show-overflow-tooltip="true" />
            <el-table-column label="卡号" prop="cardId" width="150px" :show-overflow-tooltip="true" />
            <el-table-column label="职位" prop="job" :show-overflow-tooltip="true" />
            <el-table-column label="状态" width="70px">
              <template slot-scope="scope">
                <el-tag v-if="scope.row.disabled" type="danger">停用</el-tag>
                <el-tag v-else type="success">启用</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="540px">
              <template slot-scope="scope">
                <template>
                  <el-button type="primary" size="mini" @click="setRoles(scope.row)">分配权限</el-button>
                </template>
                <template>
                  <el-button type="primary" size="mini" @click="setGroups(scope.row)">分配用户群</el-button>
                </template>
                <template>
                  <el-button type="primary" size="mini" @click="setChests(scope.row)">分配单柜</el-button>
                </template>
                <template>
                  <el-button type="primary" size="mini" @click="setChestGroups(scope.row)">分配柜组</el-button>
                </template>
                <template>
                  <el-button type="warning" size="mini" @click="openEditFormDiglog(scope.row)">编辑</el-button>
                </template>
                <template>
                  <el-button type="danger" size="mini" @click="delUser(scope.row)">删除</el-button>
                </template>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-row>
      <!-- 页条 -->
      <el-row type="flex" justify="center" class="pageRow">
        <el-pagination
          :current-page="getReq.currentPage"
          :page-sizes="[10, 25, 50]"
          :page-size="getReq.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </el-row>

      <!-- 表单对话框 -->
      <el-dialog
        :visible.sync="formDialogVisible"
        width="50%"
        top="5vh"
        :close-on-click-modal="false"
        :show-close="false"
      >
        <el-row class="formTitleRow">
          <div class="formTitle">{{ formTitle }}</div>
        </el-row>
        <el-divider />
        <el-row class="formRow">
          <el-form ref="form" :rules="rules" :model="form" label-width="120px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="用户姓名" prop="userName">
                  <el-input ref="input" v-model="form.userName" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="工号" prop="jobNumber">
                  <el-input v-model="form.jobNumber" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="请输入密码" prop="password" autocomplete="off">
                  <el-input v-model="form.password" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="再次输入密码" prop="checkPassword" autocomplete="off">
                  <el-input v-model="form.checkPassword" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="卡号" prop="cardId">
                  <el-input v-model="form.cardId" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="职位" prop="job">
                  <el-input v-model="form.job" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item v-if="formTitle === '编辑用户'" label="用户头像" prop="photoUrl">
                  <!-- <el-upload
                    v-if="form.id"
                    ref="imageDom"
                    class="avatar-uploader"
                    action="/back_front/users/uploadPhoto"
                    :data="{ userId: form.id }"
                    :show-file-list="false"
                    :headers="cpUploadHeaders"
                    :on-success="handleUploadSuccess"
                    :before-upload="handleBeforeUpload"
                    style="border: 1px dashed #DCDFE6;border-radius: 6px;width: 100px;height: 100px;text-align: center; line-height: 100px;"
                  >
                    <el-image
                      v-if="form.thumbnailImageUrl"
                      :src="cpThumbnailUrl"
                      class="avatar"
                      :style="{'width': '100px','height': '100px'}"
                    />
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                  </el-upload> -->
                 <FortenUpload
                  :title="'请上传用户头像图片'"
                  :fileRefTable="'fsd_user'"
                  :fileSavePath="'fsd_user'"
                  :fileRefId="form.id"
                  :fileType="'img'"
                  :fileSize="2"
                  :fileMaxNum="1"  :propStatus="propStatus" :readonly="false"
                ></FortenUpload>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item v-if="formTitle === '创建用户'" label="指纹数量" prop="fpNum">
              <el-input-number
                v-model="form.fpNum"
                :min="1"
                :max="10"
                label="最多可为用户设置10个指纹模板"
              ></el-input-number>
            </el-form-item>
            <el-form-item v-if="formTitle === '编辑用户'" label="指纹管理">
              <el-table :data="fpTemp" :span-method="objectSpanMethod" style="width: 100%" height="200">
                <el-table-column label="编号" width="180" v-if="false">
                  <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.id }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="名称" width="180">
                  <template slot-scope="scope">
                    <span style="margin-left: 10px">{{ scope.row.remark }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="是否重采" width="180">
                  <template slot-scope="scope">
                    <span style="margin-left: 10px" v-if="scope.row.templet != null && scope.row.templet != ''">
                      <div class="switchDiv">
                        <el-switch
                          v-model="scope.row.reCollection"
                          active-color="#ff4949"
                          inactive-color="#13ce66"
                          class="switch"
                        />
                        <div v-if="scope.row.reCollection" class="switchText">重采</div>
                      </div>
                    </span>
                    <span style="margin-left: 10px" v-else> 未采集 </span>
                  </template>
                </el-table-column>
                <!-- <el-table-column label="是否禁用" width="180">
                  <template slot-scope="scope">
                    <span style="margin-left: 10px">
                      <div class="switchDiv">
                        <el-switch
                          v-model="scope.row.discarded"
                          active-color="#ff4949"
                          inactive-color="#13ce66"
                          class="switch"
                        />
                        <div v-if="scope.row.discarded" class="switchText">禁用</div>
                        <div v-else class="switchText">启用</div>
                      </div>
                    </span>
                  </template>
                </el-table-column> -->
                <el-table-column label="操作">
                  <template slot-scope="scope" v-if="scope.$index == 0">
                    <el-button size="mini" @click="handleAdd()">新增指纹</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>
            <el-form-item v-if="formTitle === '编辑用户'" label="状态">
              <div class="switchDiv">
                <el-switch v-model="editReq.disabled" active-color="#ff4949" inactive-color="#13ce66" class="switch" />
                <div v-if="editReq.disabled" class="switchText">停用</div>
                <div v-else class="switchText">启用</div>
              </div>
            </el-form-item>
          </el-form>
        </el-row>
        <el-divider />
        <el-row>
          <div class="formButtonDiv">
            <el-button size="mini" class="formButton" @click="closeFormDialog">取 消</el-button>
            <el-button type="primary" size="mini" class="formButton" @click="submit">提 交</el-button>
          </div>
        </el-row>
      </el-dialog>
      <!-- 配置对话框 -->
      <el-dialog
        :visible.sync="configDialogVisible"
        width="50%"
        top="5vh"
        :close-on-click-modal="false"
        @close="closeConfigDialog"
      >
        <ConfigPage
          v-if="configDialogVisible"
          :in-config-target="configTarget"
          :in-config-ary="configAry"
          @submitConfig="submitConfig"
          @closeConfigPage="closeConfigDialog"
        />
        <!-- v-if="configDialogVisible" 做到创建销毁组件，可以在组件中使用生命周期钩子 -->
      </el-dialog>
    </div>
  </div>
</template>

<script>
import FortenUpload from '@/components/common/FortenUpload.vue'
import ConfigPage from '@/components/fsd/ConfigPage'
import {
  createUserAPI,
  synchronizeUsersAPI,
  getUsersAPI,
  editUserAPI,
  getFpTempAPI,
  createFpTempAPI,
  editFpTempAPI,
} from '@/util/back_front_api/users.js'
import getRelationByUserAPI from '@/util/back_front_api/mixTable.js'
import { getRolesAllAPI } from '@/util/back_front_api/roles.js'
import { getGroupsAllAPI } from '@/util/back_front_api/groups.js'
import { getChestsAndStationsAllAPI } from '@/util/back_front_api/chests.js'
import { getChestGroupsAllAPI } from '@/util/back_front_api/chestGroups.js'
import { getRolesByUserAPI, changeRolesByUserAPI } from '@/util/back_front_api/users_roles.js'
import { getGroupsByUserAPI, changeGroupsByUserAPI } from '@/util/back_front_api/groups_users.js'
import { getChestsAndStationsByUserAPI, changeChestsByUserAPI } from '@/util/back_front_api/chests_users.js'
import { getChestGroupsByUserAPI, changeChestGroupsByUserAPI } from '@/util/back_front_api/users_chestGroups.js'

export default {
  props: {
    propParent: Object,
    propInitData: Object,
    propPrimaryKey: String,
    propDictionaries: Object,
    propCurrentRow: Object,
    propViewFormData: Object,
    propReadonly: Boolean,
    propStatus: String,
    propRules: Object
  },
  components: {
    FortenUpload,
    ConfigPage,
  },
  name: 'fsduser',
  data() {
    let validatePass1 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else {
        if (value !== '') {
          this.$refs.form.validateField('checkPassword')
          callback()
        } else {
          callback()
        }
      }
    }
    let validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入密码'))
      } else if (value !== this.form.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    let validateFpNum = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入用户指纹数量'))
      } else {
        value = parseFloat(value)
        if (Number.isInteger(value)) {
          if (value <= 0) {
            callback(new Error('数量必须大于零'))
          } else {
            callback()
          }
        } else {
          callback(new Error('数量必须是整数'))
        }
      }
    }
    return {
      //同步按钮等待状态
      synchronizeUsersBtn: false,
      // 列表
      tableAry: [],
      // 页条
      total: 0,
      // 表单对话框
      formTitle: '',
      formDialogVisible: false,
      form: {
        userName: '',
        jobNumber: '',
        cardId: '',
        job: '',
        password: '',
        checkPassword: '',
        fpNum: 1,
        photoUrl: '',
        thumbnailImageUrl: '',
      },
      rules: {
        userName: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        password: [{ required: true, validator: validatePass1, trigger: 'blur' }],
        checkPassword: [{ required: true, validator: validatePass2, trigger: 'blur' }],
        jobNumber: [{ required: true, message: '请输入工号', trigger: 'blur' }],
        cardId: [{ required: true, message: '请输入卡号', trigger: 'blur' }],
        job: [{ required: true, message: '请输入岗位', trigger: 'blur' }],
        fpNum: [{ required: true, validator: validateFpNum, trigger: 'change' }],
      },
      // 配置对话框
      configDialogVisible: false,
      rolesAll: [],
      users_Roles: [],

      configTarget: {
        id: '',
        dialogTitle: '',
        itemTitle: '',
        name: '',
        type: '',
      },
      configAry: [],
      // 请求
      getReq: {
        keyword: '',
        currentPage: 1,
        pageSize: 10,
      },
      getByUserReq: {
        id: '',
      },
      createReq: {
        userName: '',
        jobNumber: '',
        cardId: '',
        job: '',
        password: '',
        fpNum: 1,
      },
      editReq: {
        id: '',
        userName: '',
        jobNumber: '',
        cardId: '',
        job: '',
        password: '',
        disabled: false,
        fpNum: 1,
      },
      changeReq: {
        id: '',
        idAry: [],
      },
      fpTemp: [
        {
          id: '',
          remark: '',
          reCollection: false,
          // discarded: false,
          version: 1,
          templet: '',
        },
      ],
    }
  },
  created() {
    // 使用keepalive后不能刷新的情况，在activated中获取list
    this.getUsers()
  },
  // computed: {
  //   cpUploadHeaders() {
  //     return {
  //       Authorization: this.utils.getCurrentUser().token,
  //     }
  //   },
  //   cpThumbnailUrl() {
  //     return `${this.form.thumbnailImageUrl}?temp=${Math.random()}`
  //   },
  // },
  methods: {
    // handleUploadSuccess(res, file) {
    //   if (res.success) {
    //     this.$set(this.form, 'photoUrl', res.data.url)
    //     this.$set(this.form, 'thumbnailImageUrl', '')
    //     this.$nextTick(() => {
    //       this.$set(this.form, 'thumbnailImageUrl', res.data.thumbnailUrl)
    //     })
    //     this.$forceUpdate()
    //     this.getUsers()
    //   } else {
    //     this.utilMessage.error(`上传文件返回错误：${res.msg}`)
    //   }
    // },
    // handleBeforeUpload(file) {
    //   const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
    //   const isLt2M = file.size / 1024 / 1024 < 2
    //   if (!isJPG) {
    //     this.utilMessage.error('上传头像图片只能是 JPG/PNG 格式!')
    //   }
    //   if (!isLt2M) {
    //     this.utilMessage.error('上传头像图片大小不能超过 2MB!')
    //   }
    //   return isJPG && isLt2M
    // },
    // 功能条
    clearKeyword() {
      this.getReq.keyword = ''
      this.getUsers()
    },
    search() {
      this.getReq.currentPage = 1
      this.getUsers()
    },
    async handleAdd() {
      if (this.fpTemp.length >= 10) {
        this.utilMessage.warning('单个用户最多可录入十个指纹')
        return
      }
      this.fpTemp = []
      await createFpTempAPI({ userId: this.editReq.id })
      this.fpTemp = (await getFpTempAPI({ userId: this.editReq.id })).data
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      // if (columnIndex === 2) {
      //   return {
      //     rowspan: this.fpTemp.length,
      //     colspan: 1,
      //   }
      // }
    },
    // 列表
    async expandTable(row) {
      let result = []
      row.hasGroups = ''
      row.hasRoles = ''
      row.hasChests = ''
      row.hasChestGroups = ''

      this.getByUserReq.id = row.id
      result = (await getRelationByUserAPI(this.getByUserReq)).data
      const [rolesByUser, chestByUser, chestGroupByUser, groupByUser, chestByChestGroup, roleByGroup] = result

      groupByUser.forEach((item) => {
        if (row.hasGroups === '') {
          row.hasGroups = item.groups.groupName
        } else {
          row.hasGroups = row.hasGroups + '、' + item.groups.groupName
        }
      })

      chestGroupByUser.forEach((item) => {
        if (row.hasChestGroups === '') {
          row.hasChestGroups = item.chestGroups.chestGroupName
        } else {
          row.hasChestGroups = row.hasChestGroups + '、' + item.chestGroups.chestGroupName
        }
      })

      let rolesUnique = new Set()
      rolesByUser.forEach((item) => {
        rolesUnique.add(item.roles.roleName)
      })
      roleByGroup.forEach((item) => {
        rolesUnique.add(item.roles.roleName)
      })
      rolesUnique.forEach((item) => {
        if (row.hasRoles === '') {
          row.hasRoles = item
        } else {
          row.hasRoles = row.hasRoles + '、' + item
        }
      })

      let chestsUnique = new Set()
      chestByUser.forEach((item) => {
        chestsUnique.add(item.chests.stations.stationName + '-' + item.chests.chestNo)
      })
      chestByChestGroup.forEach((item) => {
        chestsUnique.add(item.chests.stations.stationName + '-' + item.chests.chestNo)
      })
      let chestSplit = []
      chestsUnique.forEach((item) => {
        const ary = item.split('-')
        chestSplit.push(ary)
      })
      let chestArrangeChestNo = []
      chestSplit.forEach((item) => {
        let objTemp = {}
        let flag = true
        for (let i = 0; i < chestArrangeChestNo.length; i += 1) {
          if (item[0] === chestArrangeChestNo[i].stationName) {
            chestArrangeChestNo[i].chestNo = chestArrangeChestNo[i].chestNo + '、' + item[1]
            flag = false
            break
          }
        }
        if (flag) {
          objTemp.stationName = item[0]
          objTemp.chestNo = item[1]
          chestArrangeChestNo.push(objTemp)
        }
      })
      chestArrangeChestNo.forEach((item) => {
        if (row.hasChests === '') {
          row.hasChests = item.stationName + '(' + item.chestNo + ')'
        } else {
          row.hasChests = row.hasChests + '、' + item.stationName + '(' + item.chestNo + ')'
        }
      })
      if (row.hasGroups === '') {
        row.hasGroups = '（无）'
      }
      if (row.hasRoles === '') {
        row.hasRoles = '（无）'
      }
      if (row.hasChests === '') {
        row.hasChests = '（无）'
      }
      if (row.hasChestGroups === '') {
        row.hasChestGroups = '（无）'
      }
    },
    delUser() {},
    // 页条
    handleSizeChange(size) {
      this.getReq.pageSize = size
      this.getUsers()
    },
    handleCurrentChange(page) {
      this.getReq.currentPage = page
      this.getUsers()
    },
    // 表单对话框
    openCreateFormDialog() {
      this.formDialogVisible = true

      this.$nextTick(() => {
        this.$refs.input.focus()
        this.$refs.form.resetFields()

        this.formTitle = '创建用户'
      })
    },
    // 同步SPD提供的用户视图中的用户
    synchronizeUsers() {
      this.synchronizeUsersBtn = true
      synchronizeUsersAPI()
        .then((res) => {
          this.utilMessage.success(res.msg)
          setTimeout(() => {
            this.getUsers()
          }, 500)
          this.synchronizeUsersBtn = false
        })
        .catch((err) => {
          this.synchronizeUsersBtn = false
        })
    },
    openEditFormDiglog(row) {
      this.editReq.id = ''
      this.editReq.userName = ''
      this.editReq.jobNumber = ''
      this.editReq.cardId = ''
      this.editReq.job = ''
      this.editReq.password = ''

      this.formDialogVisible = true
      this.fpTemp = []

      this.$nextTick(async () => {
        this.$refs.input.focus()
        this.$refs.form.resetFields()

        this.formTitle = '编辑用户'

        this.form.userName = row.userName
        this.form.password = row.password
        this.form.checkPassword = row.password
        this.form.jobNumber = row.jobNumber
        this.form.cardId = row.cardId
        this.form.job = row.job
        this.form.id = row.id
        this.form.photoUrl = row.photoUrl
        this.form.thumbnailImageUrl = row.thumbnailImageUrl

        this.editReq.disabled = row.disabled
        this.editReq.id = row.id
        this.fpTemp = (await getFpTempAPI({ userId: row.id })).data
      })
    },
    closeFormDialog() {
      this.formTitle = ''
      this.formDialogVisible = false
    },
    create() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('将会创建你所设置的用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.createReq.userName = this.form.userName
              this.createReq.jobNumber = this.form.jobNumber
              this.createReq.cardId = this.form.cardId
              this.createReq.job = this.form.job
              this.createReq.password = this.form.password
              this.createReq.fpNum = this.form.fpNum
              createUserAPI(this.createReq)
                .then((res) => {
                  this.utilMessage.success(res.msg)
                  setTimeout(() => {
                    this.getUsers()
                  }, 500)
                })
                .catch((err) => {
                  console.log(err)
                })
              this.closeFormDialog()
            })
            .catch(() => {
              return false
            })
        } else {
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    edit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.$confirm('将会修改你所选的用户的信息, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
            .then(() => {
              this.editReq.userName = this.form.userName
              this.editReq.jobNumber = this.form.jobNumber
              this.editReq.cardId = this.form.cardId
              this.editReq.job = this.form.job
              this.editReq.password = this.form.password
              this.editReq.fpNum = this.fpTemp.length
              editUserAPI(this.editReq)
                .then((res) => {
                  if (res.success) {
                    editFpTempAPI(this.fpTemp).then((re) => {
                      if (!re.success) {
                        this.utilMessage.error(res.msg)
                      }
                    })
                  }
                  this.utilMessage.success(res.msg)
                  setTimeout(() => {
                    this.getUsers()
                  }, 500)
                })
                .catch((err) => {
                  console.log(err)
                })
              this.closeFormDialog()
            })
            .catch(() => {
              return false
            })
        } else {
          console.log('error submit!!')
          this.utilMessage.warning('请正确输入信息。')
          return false
        }
      })
    },
    submit() {
      if (this.formTitle === '创建用户') {
        this.create()
      } else if (this.formTitle === '编辑用户') {
        this.edit()
      } else {
        this.utilMessage.warning('formTitle有误。')
      }
    },
    // 配置对话框
    async setRoles(row) {
      this.configAry = [] // configTarget赋值

      this.configTarget.dialogTitle = '分配该用户所拥有的权限'
      this.configTarget.itemTitle = '请选择权限：'
      this.configTarget.name = row.userName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      this.getByUserReq.id = row.id

      let rolesAll = [] // configAry赋值
      let rolesByUser = []
      try {
        rolesAll = (await getRolesAllAPI()).data
        rolesByUser = (await getRolesByUserAPI(this.getByUserReq)).data
      } catch (err) {
        console.log(err)
      }

      let obj = {}
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      rolesAll.forEach((roleInRolesAll) => {
        let objItem = {}
        objItem.id = roleInRolesAll.id
        objItem.display = roleInRolesAll.roleName
        objItem.col = 6
        objItem.checked = false
        for (let i = 0; i < rolesByUser.length; i += 1) {
          if (roleInRolesAll.id === rolesByUser[i].roleId) {
            objItem.checked = true
            rolesByUser.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    async setGroups(row) {
      this.configAry = []

      this.configTarget.dialogTitle = '分配该用户所属的用户群'
      this.configTarget.itemTitle = '请选择用户群：'
      this.configTarget.name = row.userName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      this.getByUserReq.id = row.id

      let groupsAll = []
      let groupsByUser = []
      try {
        groupsAll = (await getGroupsAllAPI()).data
        groupsByUser = (await getGroupsByUserAPI(this.getByUserReq)).data
      } catch (err) {
        console.log(err)
      }

      let obj = {}
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      groupsAll.forEach((groupInGroupsAll) => {
        let objItem = {}
        objItem.id = groupInGroupsAll.id
        objItem.display = groupInGroupsAll.groupName
        objItem.col = 6
        objItem.checked = false
        for (let i = 0; i < groupsByUser.length; i += 1) {
          if (groupInGroupsAll.id === groupsByUser[i].groupId) {
            objItem.checked = true
            groupsByUser.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    async setChests(row) {
      let checkItemTemp = []
      let noSameStation = true

      this.configAry = []
      this.configTarget.dialogTitle = '分配该用户所拥有的智能柜使用权'
      this.configTarget.itemTitle = '请选择智能柜：'
      this.configTarget.name = row.userName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      let chestsAndStationsAll = [] // configAry赋值
      let chestsAndStationsByUser = []
      this.getByUserReq.id = row.id
      try {
        chestsAndStationsAll = (await getChestsAndStationsAllAPI()).data
        chestsAndStationsByUser = (await getChestsAndStationsByUserAPI(this.getByUserReq)).data
      } catch (err) {
        console.log(err)
      }

      chestsAndStationsAll.forEach((chestInChestsAndStationsAll) => {
        let objItem = {}
        objItem.id = chestInChestsAndStationsAll.id
        objItem.display = chestInChestsAndStationsAll.chestNo
        objItem.col = 6
        objItem.checked = false
        objItem.stationId = chestInChestsAndStationsAll.stationId
        objItem.stationName = chestInChestsAndStationsAll.stations.stationName
        for (let i = 0; i < chestsAndStationsByUser.length; i += 1) {
          if (chestInChestsAndStationsAll.id === chestsAndStationsByUser[i].chestId) {
            objItem.checked = true
            chestsAndStationsByUser.splice(i, 1)
            break
          }
        }
        checkItemTemp.push(objItem)
      })

      checkItemTemp.forEach((item) => {
        noSameStation = true
        for (let i = 0; i < this.configAry.length; i += 1) {
          if (item.stationId === this.configAry[i].id) {
            delete item.stationId
            delete item.stationName
            if (this.configAry[i].checkItem) {
              this.configAry[i].checkItem.push(item)
            } else {
              this.configAry[i].checkItem = []
              this.configAry[i].checkItem.push(item)
            }
            noSameStation = false
            break
          }
        }
        if (noSameStation) {
          let obj = {}
          obj.id = item.stationId
          obj.title = item.stationName
          delete item.stationId
          delete item.stationName
          obj.checkItem = []
          obj.checkItem.push(item)
          this.configAry.push(obj)
        }
      })

      this.configDialogVisible = true
    },
    async setChestGroups(row) {
      this.configAry = []

      this.configTarget.dialogTitle = '分配该用户所拥有的智能柜组使用权'
      this.configTarget.itemTitle = '请选择智能柜组：'
      this.configTarget.name = row.userName
      this.configTarget.id = row.id
      this.configTarget.type = 'checkbox'

      this.getByUserReq.id = row.id

      let chestGroupsAll = []
      let chestGroupsByUser = []
      try {
        chestGroupsAll = (await getChestGroupsAllAPI()).data
        chestGroupsByUser = (await getChestGroupsByUserAPI(this.getByUserReq)).data
      } catch (err) {
        console.log(err)
      }

      let obj = {}
      obj.id = '0'
      obj.checkItem = []
      obj.title = ''
      chestGroupsAll.forEach((chestGroupInChestGroupsAll) => {
        let objItem = {}
        objItem.id = chestGroupInChestGroupsAll.id
        objItem.display = chestGroupInChestGroupsAll.chestGroupName
        objItem.col = 6
        objItem.checked = false
        for (let i = 0; i < chestGroupsByUser.length; i += 1) {
          if (chestGroupInChestGroupsAll.id === chestGroupsByUser[i].chestGroupId) {
            objItem.checked = true
            chestGroupsByUser.splice(i, 1)
            break
          }
        }
        obj.checkItem.push(objItem)
      })
      this.configAry.push(obj)

      this.configDialogVisible = true
    },
    closeConfigDialog() {
      this.configDialogVisible = false
    },
    async submitConfig(outObj) {
      console.log(outObj)
      let msg
      this.closeConfigDialog()

      if (outObj.title === '分配该用户所拥有的权限') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.userId = outObj.targetId
          tempObj.roleId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeRolesByUserAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配该用户所属的用户群') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.userId = outObj.targetId
          tempObj.groupId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeGroupsByUserAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配该用户所拥有的智能柜使用权') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []

        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.userId = outObj.targetId
          tempObj.chestId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeChestsByUserAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else if (outObj.title === '分配该用户所拥有的智能柜组使用权') {
        this.changeReq.id = outObj.targetId
        this.changeReq.idAry = []
        outObj.configId.forEach((item) => {
          let tempObj = {}
          tempObj.userId = outObj.targetId
          tempObj.chestGroupId = item
          this.changeReq.idAry.push(tempObj)
        })
        try {
          msg = (await changeChestGroupsByUserAPI(this.changeReq)).msg
          this.utilMessage.success(msg)
        } catch (err) {
          console.log(err)
        }
      } else {
        this.utilMessage.warning('提交配置种类出错')
      }
    },
    getUsers() {
      getUsersAPI(this.getReq)
        .then((result) => {
          this.total = result.data.count
          let indexTemp = (this.getReq.currentPage - 1 >= 0 ? this.getReq.currentPage - 1 : 0) * this.getReq.pageSize
          this.tableAry = result.data.rows.map((item) => {
            this.$set(item, 'hasRoles', '')
            this.$set(item, 'hasGroups', '')
            this.$set(item, 'hasChests', '')
            this.$set(item, 'hasChestGroups', '')
            this.$set(item, 'index', (indexTemp += 1))
            return item
          })
        })
        .catch((err) => {
          console.log(err)
        })
    },
  },
}
</script>

<style lang="scss" scoped>
.buttonRow {
  margin: 10px;
}
.tableRow {
  margin: 10px;
}
.tableDiv {
  height: 530px;
  overflow-y: scroll;
}
.pageRow {
  margin: 5px;
}
.table-expand {
  font-size: 0;
}
.table-expand label {
  width: 90px;
  color: #99a9bf;
}
.table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 100%;
}
.switch {
  margin: 0px 10px 0px 0px;
}
.switchText {
  display: inline-block;
}
.formTitle {
  text-align: center;
  letter-spacing: 10px;
  font-size: 20px;
}
.formRow {
  padding: 0px 100px 0px 100px;
}
.formButtonDiv {
  text-align: center;
}
.formButton {
  margin: 0px 30px 0px 30px;
}
.el-table th.gutter {
  display: table-cell !important;
}
// 滚动条
::-webkit-scrollbar {
  width: 3px;
}
::-webkit-scrollbar-thumb {
  background: #bcddff;
  border-radius: 5px;
}
</style>
